import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import JwtConfig from '../../../../../config/jwt.config';
import { UserService } from '../user/user.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly userService: UserService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: JwtConfig.secret,
    });
  }

  async validate(payload: any) {
    // 在这里进行用户验证逻辑
    const loginName: string = payload.loginName;
    const userInfo = await this.userService.findUserByName(loginName);
    // 验证用户状态 0:禁用 1:正常
    if (userInfo[0].state === 0) {
      throw new UnauthorizedException('用户被禁用');
    }
    // 返回一个包含用户信息的对象
    return userInfo[0];
  }
}
